import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { ClsCrhNavbarDto } from '../crh-navbar/cls-crh-navbar-dto';
import { SelectItem } from 'primeng/api';

import { CompanyService } from '../company.service';
import { ClsCompanyModel, ClsProductModel } from '../models/cls-company-model'; 


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  navDto       : ClsCrhNavbarDto;
  types        : SelectItem[];
  selectedType : string;
  isCompanyComp: boolean;
  keywords     : string; // 搜索关键字

  // 分页数据
  arrCompanys  : ClsCompanyModel[];
  arrProducts  : ClsProductModel[];
  totalRecords : number = 0;
  sortField    : string = "abc";
  sortOrder    : string = "asc";
  emptyMessage : string = "无数据";
  loading      : string = "加载中";

  constructor(private companyService: CompanyService, private sanitize:DomSanitizer) { }

  ngOnInit() {

      this.selectedType = 'company';
      this.isCompanyComp = true;

      this.navDto =  {
          title : "搜索关键字",

          leftBarItem : false,
          leftBarItemIconCls :"pi-chevron-left",

          rightBarItem : true,
          rightBarItemIconCls :"pi-refresh",

          leftBarClick : function(){
             
          },

          rightBarClick : function(){
            window.location.reload();
          }
      };

      this.types = [
        {label: '搜供应商', value: 'company', icon: 'fa fa-fw fa-cc-paypal'},
        {label: '搜产品名', value: 'product', icon: 'fa fa-fw fa-cc-visa'}
    ];

  }

  getCompanys(pageParam : object){
    let self = this;
    pageParam["kind"] = this.selectedType == "company" ? "1" : "2";
    pageParam["keywords"] = this.keywords || "";

    this.companyService.getCompanys(pageParam).subscribe(data => {
        if(!data.flag){
            console.log("失败了：", data.msg);
            return;
        }
        if(self.isCompanyComp){
          this.arrCompanys = data.data.data as ClsCompanyModel[];
          if(this.keywords){
              this.arrCompanys = this.arrCompanys.map(function(ele){
                let arr : string[] = [];
                for (const c of pageParam["keywords"]) {
                    if(arr.join(",").indexOf(c) != -1){
                        continue;
                    }
                    let reg = new RegExp(c, "gi"); 
                    ele.COMP_NAME = ele.COMP_NAME.replace(reg,'<span style="color:red">'+ c +'</span>');
                    arr.push(c);
                }
                ele.COMP_NAME = self.sanitize.bypassSecurityTrustHtml(ele.COMP_NAME)
                return ele;
              });
          }
        }else{
          this.arrProducts = data.data.data as ClsProductModel[];
          if(this.keywords){
              this.arrProducts = this.arrProducts.map(function(ele){
                let arr : string[] = [];
                for (const c of pageParam["keywords"]) {
                    if(arr.join(",").indexOf(c) != -1){
                        continue;
                    }
                    let reg = new RegExp(c, "gi"); 
                    ele.PDT_NAME = ele.PDT_NAME.replace(reg,'<span style="color:red">'+ c +'</span>');
                    arr.push(c);
                }
                ele.PDT_NAME = self.sanitize.bypassSecurityTrustHtml(ele.PDT_NAME)
                return ele;
              });
          }
        }
       

        this.totalRecords = data.data.total; 
    });    
  }

  loadData(event) {
    //event.first = First row offset
    //event.rows = Number of rows per page
    let pageIndex = event.first / event.rows;
    let pageSize = event.rows ;
    this.getCompanys({ page:pageIndex, rows: pageSize});
  }

  // 搜索按钮事件
  searchButtonHandleClick(event){
      if(this.keywords != undefined){
          this.getCompanys({ page:0, rows: 20});
      }
  }

  companyOrProductChange(event){
    let val = event.value;
    this.isCompanyComp = (val == "company");
  }
}
